/*
 * commons is a based project implemented
 * Copyright (C) 2024 Jasmine
 */
package com.commons.core.utils;

import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;

import org.springframework.util.StringUtils;

import com.commons.core.function.Fn;

/**
 * @author Jasmine
 * @version 1.0
 * @date 2021-09-18 11:33:33
 * @see ColumnUtil
 * @since JDK1.8
 */
public class ColumnUtil {
    /**
     * 下划线字符
     */
    public static final char UNDERLINE = '_';

    private static final Pattern GET_PATTERN = Pattern.compile("^get[A-Z].*");
    private static final Pattern IS_PATTERN = Pattern.compile("^is[A-Z].*");
    private static Pattern humpPattern = Pattern.compile("[A-Z]");
    private static Pattern linePattern = Pattern.compile("_(\\w)");

    /**
     * 注意: 非标准变量（非小驼峰）调用这个方法可能会有问题
     *
     * @param fn
     * @param <T>
     * @return
     */
    public static <T> String fnToFieldName(Fn<T, ?> fn) {
        try {
            // 从function取出序列化方法
            Method method = fn.getClass().getDeclaredMethod("writeReplace");
            method.setAccessible(Boolean.TRUE);
            SerializedLambda serializedLambda = (SerializedLambda)method.invoke(fn);
            String getter = serializedLambda.getImplMethodName();
            // 对于非标准变量生成的Get方法这里可以直接抛出异常，或者打印异常日志
            if (GET_PATTERN.matcher(getter).matches()) {
                getter = getter.substring(3);
            } else if (IS_PATTERN.matcher(getter).matches()) {
                getter = getter.substring(2);
            }
            return camelToUnderline(firstToLowerCase(getter));
            // return Introspector.decapitalize(getter);
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 字符串驼峰转下划线格式
     *
     * @param camelCaseStr 需要转换的字符串
     * @return 转换好的字符串
     */
    public static String camelToUnderline(String camelCaseStr) {
        if (!StringUtils.hasText(camelCaseStr)) {
            return "";
        }
        // 全小写
        if (camelCaseStr.toLowerCase().equals(camelCaseStr)) {
            return camelCaseStr;
        }
        // 全大写直接return小写
        if (camelCaseStr.toUpperCase().equals(camelCaseStr)) {
            return camelCaseStr.toLowerCase();
        }
        int len = camelCaseStr.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = camelCaseStr.charAt(i);
            if (Character.isUpperCase(c) && i > 0) {
                sb.append(UNDERLINE);
            }
            sb.append(Character.toLowerCase(c));
        }
        return sb.toString();
    }

    /**
     * 字符串下划线转驼峰格式
     *
     * @param snakeCaseStr 需要转换的字符串
     * @return 转换好的字符串
     */
    public static String underlineToCamel(String snakeCaseStr) {
        if (!StringUtils.hasText(snakeCaseStr)) {
            return "";
        }
        // 不包含_
        if (!snakeCaseStr.contains(UNDERLINE + "")) {
            // 全大写直接return小写
            if (snakeCaseStr.toUpperCase().equals(snakeCaseStr)) {
                return snakeCaseStr.toLowerCase();
            }
            // 其他return 首字母小写
            else {
                return firstToLowerCase(snakeCaseStr);
            }
        }

        String temp = snakeCaseStr.toLowerCase();
        int len = temp.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = temp.charAt(i);
            if (c == UNDERLINE) {
                if (++i < len) {
                    sb.append(Character.toUpperCase(temp.charAt(i)));
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 首字母转换小写
     *
     * @param param 需要转换的字符串
     * @return 转换好的字符串
     */
    public static String firstToLowerCase(String param) {
        if (!StringUtils.hasText(param)) {
            return "";
        }
        return param.substring(0, 1).toLowerCase() + param.substring(1);
    }

    public static List<Field> getAllFieldsArray(Class<?> cls) {
        Objects.requireNonNull(cls, "cls");
        List<Field> allFields = new ArrayList<>();

        // 获取当前类的所有属性
        Field[] currentFields = cls.getDeclaredFields();

        Arrays.stream(currentFields).filter(field -> !Modifier.isStatic(field.getModifiers()))
            .forEach(v -> allFields.add(v));

        // 获取父类的所有属性
        for (Class<?> parentClass = cls.getSuperclass(); parentClass != null;
            parentClass = parentClass.getSuperclass()) {
            Field[] parentFields = parentClass.getDeclaredFields();

            // 避免重复添加相同的属性 及去除 静态属性如:serialVersionUID
            for (Field parentField : parentFields) {
                String name = parentField.getName();
                if (!allFields.stream().anyMatch(v -> v.getName().equalsIgnoreCase(name))
                    && !Modifier.isStatic(parentField.getModifiers())) {
                    allFields.add(parentField);
                }
            }
        }
        // return allFields.toArray(ArrayUtils.EMPTY_FIELD_ARRAY);
        return allFields;
    }
}
